/**
 * 
 * @param value
 * @return
 * 判断是否具有超过小数点后多位的数字
 */
function isTriDecimal(value , dnum){    
                if(value!=null&&value!=''){    
                    var decimalIndex=value.indexOf('.');    
                    if(decimalIndex=='-1'){    
                        return false;    
                    }else{    
                        var decimalPart=value.substring(decimalIndex+1,value.length);    
                        if(decimalPart.length>dnum){    
                            return true;    
                        }else{    
                            return false;    
                        }    
                    }    
                }    
                return false;    
 };
/**
 * 获得上下文路径
 */
 $.getContextPath = function () {
    var pathName = document.location.pathname;
    var index = pathName.substr(1).indexOf("/");
    var result = pathName.substr(0,index+1);
    return result;
 };
/**
 * 字符串替换
 */
 /*common method*/
 $.format = function () {
     var s = arguments[0];
     for (var i = 0; i < arguments.length - 1; i++) {
         var reg = new RegExp("\\{" + i + "\\}", "gm");
         s = s.replace(reg, arguments[i + 1]);
     }
     return s;
 };

//获得类型
 $.typeOf = function (value) {
     var oP = Object.prototype, toString = oP.toString;
     if (null === value) {
         return 'null';
     }

     var type = typeof value;
     if ('undefined' === type || 'string' === type) {
         return type;
     }

     var typeString = toString.call(value);
     switch (typeString) {
     case '[object Array]': return 'array';
     case '[object Date]': return 'date';
     case '[object Boolean]': return 'boolean';
     case '[object Number]': return 'number';
     case '[object Function]': return 'function';
     case '[object RegExp]': return 'regexp';
     case '[object Object]':
         if (undefined !== value.nodeType) {
             if (3 == value.nodeType) {
                 return (/\S/).test(value.nodeValue) ? 'textnode': 'whitespace';
             } else {
                 return 'element';
             }
         } else {
             return 'object';
         }
     default:
         return 'unknow';
     }
 };

 //生成表格
 $.fn.genGrid = function(options, data){
     var gridTpl = '<table id="gridTable_{0}"></table><div id="pager_{0}"></div>',
         $gridTable, me = this[0], id = me.id, $gridDiv = $(me), 
         _pid = '#pager_'+id, _gid = '#gridTable_' + id;
     
         
     //清空原有表格内容
     if (id === 'undefined') return false;
     $gridDiv.empty().append($.format(gridTpl,id));
     
     var pos = $(me).position(), bh = document.body.scrollHeight,
         height = bh - pos.top - 80, loadComplete = options.loadComplete,
         footers = null;
     
     if (options.report) {
         options.reportFormat = true;
         options.loadComplete = function(data) {
             if (!data || !data.rows) return;
            var chartData = {footers: footers, bodys: data.rows};
            var chartOpts = $.table2chart(chartData, options.tempIndexes, options.tempNames);
            if (loadComplete) loadComplete(chartOpts);
        };
     }
     
     if (options.reportFormat) {
         options = $.extend({
             jsonReader: {
                 root: 'rows',
                 page: 'page',
                 total: 'total',
                 records: 'records',
                 userData: 'userData',
                 repeatitems: false,
                 id: "time"
             }
          }, options);
     }
     
     //表格默认值
     options = $.extend({
         height: height,
         datatype: 'local',
         altRows : true,
         viewrecords: true,
         rowNum: 15,
         rowList:[15,30,50],
         pager: _pid
     }, options);
     
     //重建表格
     $gridTable = $gridDiv.find(_gid);
     $gridTable.jqGrid(options);
     $gridTable.jqGrid('navGrid',_pid,{edit:false,add:false,del:false});
     if (options.groupHeaders) {
         $gridTable.jqGrid('setGroupHeaders', {
             useColSpanStyle: true, 
             groupHeaders: options.groupHeaders    
         });
     }
     
     var interval = null;
     var footerMark = $('<div class="footer-mark"><div class="progress-bar"><span class="label">正在统计数据，请稍后...</span></div></div>');
     
     $gridTable = $.extend($gridTable, {
         setRowDatas: function(data){
             for(var i=0, max=data.length; i<max; i++) {
                 $gridTable.jqGrid('addRowData', i+1, data[i]);
             }
         },
         setFooterDatas: function(data){
             footers = data;
             $gridTable.jqGrid('footerData', 'set', data);
             clearInterval(interval);
             footerMark.remove();
             $gridTable.trigger("reloadGrid");
         }
     });
     
     
     if (options.report) {
         var progress = 0;
         var progressbar = $(me).find('.ui-jqgrid-sdiv').append(footerMark)
             .find('.progress-bar').progressbar({
                 value: progress
             });
         interval = setInterval(function(){
             $.ajax({
                 url: options.url + '/progress',
                 dataType: 'json',
                 type: 'get',
                 success: function(val){
                     progressbar.progressbar({ value: val.progress });
                 }
             });
         }, 1000);
     }
     
     if (data) {
         //data.bodys && $gridTable.setRowDatas(data.bodys);
         data.footers && $gridTable.setFooterDatas(data.footers);
     }
     
     if (typeof options.gridFormComplete == 'function')
         options.gridFormComplete.call($gridTable);
     
     return $gridTable;
 };
 
 //根据表格数据生成图表
 $.table2chart = function(data, tempIndexes, tempNames) {
     var x_cats = [], series = [], 
         bodys = data.bodys || [],
         footers = data.footers || [],
         getV = function(val) {
            if (val) {
                if (typeof val == "object") return parseFloat(val.value);
                return parseFloat(val);
            }
            return 0;
        };
     
     for (var i=0, bmax=bodys.length; i<bmax; i++) {
        var btemp = bodys[i];
        x_cats.push(btemp.time);
        for (var j=0, cmax=tempIndexes.length; j<cmax; j++) {
            series[j] = series[j] || {name: tempNames[j], data: []};
            series[j].data.push(getV(btemp[tempIndexes[j]]));
        }
     }
    
     for (var i=0, bmax=footers.length; i<bmax; i++) {
        var btemp = footers[i]; if (btemp.time == '有效率') continue;
        x_cats.push(btemp.time);
        for (var j=0, cmax=tempIndexes.length; j<cmax; j++) {
            series[j] = series[j] || {name: tempNames[j], data: []};
            series[j].data.push(getV(btemp[tempIndexes[j]]));
        }
     }
    
     return { x_cats: x_cats, series: series };
 };
/**
 * 为表格生成tip
 */
$.genTableTip = function (flags) {
    for (var key in flags) {
        if (flags.hasOwnProperty(key)) {
            $('.' + key).tipTip().css({color: "red"}).parent().removeAttr('title');
        }
    }
};
/**
 * 将数值转换为指定格式的对象
 */
 $.array2obj = function(array) {
     var result = {};
     for (var i = 0; i < array.length; i++) {
         var obj = array[i];
         if (result.hasOwnProperty(obj.name)) {
             var temp = result[obj.name];
             if (Object.prototype.toString.call(temp).indexOf('Array') != -1) {
                 temp.push(obj.value);
             } else {
                 result[obj.name] = [temp, obj.value];
             }
         } else {
             result[obj.name] = obj.value;
         }
     }
     return result;
 };

 /**
  *    @options = {
  *        title:''
  *        ,subtitle:''
  *        ,ytitle:''
  *        ,tip: function(){}
  *        ,x_cats: []
  *        ,series: []
  *    }
  */
 $.fn.genLineChart = function (options) {
     return $(this).each(function(){
         var me = this, 
             config = $.extend({
                 chart: {
                     renderTo: me.id,
                     type: 'line',
                     marginRight: 130,
                     marginBottom: 45,
                     width: options.width
                 },
                 title: {
                     text: '查询图表',
                     x: -20 //center
                 },
                 subtitle: {
                     text: '',
                     x: -20
                 },
                 xAxis: {
                     categories: []
                 },
                 yAxis: {
                     plotLines: [{
                         value: 0,
                         width: 1,
                         color: '#808080'
                     }]
                 },
                 tooltip: {
                     formatter: function() {
                         return '<b>'+ this.series.name +'</b><br/>'+this.x +': '+ this.y +'°C';
                     }
                 },
                 legend: {
                     layout: 'vertical',
                     align: 'right',
                     verticalAlign: 'top',
                     x: -10,
                     y: 100,
                     borderWidth: 0
                 },
                 series: []
             }, {
                 tooltip: {
                     formatter: options.tip
                 },
                 title: {
                     text: options.title
                 },
                 subtitle: {
                     text: options.subtitle
                 },
                 xAxis: {
                     categories: options.x_cats
                 },
                 yAxis: {
                     title: {
                         text: options.ytitle
                     }
                 },
                 series: options.series
             });
                 
             return new Highcharts.Chart(config);
     });
     
 };

 $.fn.genBarChart = function (options) {
     return $(this).each(function() {
         var me = this, config = $.extend({
            chart: {
                 type: 'column'
            },
            title: {
                text: 'Bar Data'
            },
            subtitle: {
                text: 'Bar Data'
            },
            xAxis: {
                categories: []
            },
            yAxis: {
                title: {
                    text: 'Value'
                }
            }
         }, {
            tooltip: {
                formatter: options.tip
            },
            title: {
                text: options.title
            },
            subtitle: {
                text: options.subtitle
            },
            xAxis: {
                categories: options.x_cats
            },
            yAxis: {
                title: {
                    text: options.ytitle
                }
            },
            series: options.series
        });
        new Highcharts.Chart(config);
     });
 }
 
 $.fn.genLiveLineChart = function(options) {
     return $(this).each(function() {
         var me = this, config = $.extend({
             chart: {
                renderTo: me.id,
                type: 'spline',
                marginRight: 10,
                events: {
                    load: function() {
    
                        // set up the updating of the chart each 3 seconds
                        var series = this.series[0];
                        setInterval(function() {
//                            var x = (new Date()).getTime(), // current time
//                                y = Math.random();
//                            series.addPoint([x, y], true, true);
                            $.ajax({
                                url: options.url,
                                dataType: 'json',
                                type: 'get',
                                data: options.data,
                                success: function(data) {
                                    if (data === undefined) return;
                                    var x = (new Date()).getTime(), // current time
                                        y = parseFloat(new Number(data).toFixed(2));
                                    series.addPoint([x, y], true, true);
                                }
                            });
                        }, 3000);
                    }
                }
            },
            title: {
                text: 'Live Data'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150
            },
            yAxis: {
                title: {
                    text: 'Value'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/>'+
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
                        Highcharts.numberFormat(this.y, 2);
                }
            },
            legend: {
                enabled: false
            },
            exporting: {
                enabled: false
            },
            series: [{
                name: options.ytitle,
                data: options.series//[{x: 1354061485570,y:0},{x: 1354061485570,y:0}]
                /*(function() {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;
    
                    for (i = -19; i <= 0; i++) {
                        data.push({
                            x: time + i * 1000,
                            y: Math.random()
                        });
                    }
                    
                    return data;
                })()*/
            }]
         }, {
            title: {
                text: options.title
             },
             yAxis: {
                title: {
                    text: options.ytitle
                }
             },
             xAxis: {
             	categories: options.categories
             }
         });
         new Highcharts.Chart(config);
     });
     
 };

 $.fn.chartControll = function(opt) {
    return $(this).each(function(){
        var al = $('<a href="javascript:void(0)" title="上一个参数"></a>').css({
            position: 'absolute',
            display: 'inline-block',
            top: 0,
            left: 0,
            height: 50,
            width: 26,
            background: 'url(' + $.getContextPath() + '/resources/images/dir.png)',
            'background-position': '-83px -1px'
        }).click(function(){ if (typeof opt.left == 'function') opt.left(); }),
        ar = $('<a href="javascript:void(0)" title="下一个参数"></a>').css({
            position: 'absolute',
            display: 'inline-block',
            top: 0,
            right: 0,
            height: 50,
            width: 26,
            background: 'url(' + $.getContextPath() + '/resources/images/dir.png)',
            'background-position': '-28px -1px'
        }).click(function(){ if (typeof opt.right == 'function') opt.right(); });
        $(this).css({position: 'relative', overflow: 'hidden'})
            .append(al).append(ar);
    }); 
 };
 
 $.fn.setOptions = function(options){
     var optTpl = '<option value="{0}">{0}</option>';
     return $(this).each(function(){
         if (this.tagName != 'SELECT') return;
         if ($.typeOf(options) == 'array') {
             for(var i=0, max=options.length; i<max; i++) {
                 $(this).append($.format(optTpl, options[i]));
             }
         }
         
     });
};

$.trim = function (str) {
    if (typeof str != 'string') return '';
    return  str.replace(/(^\s*)|(\s*$)/g, "");
};

$.getDate = function(type) {
    var d = new Date();
    switch(type) {
    case "hour":
        return d.getHours();
    case "minute":
        return d.getMinutes();
    case "second":
        return d.getSeconds();
    case "week":
        var dstart = new Date(d.getFullYear(), "0", "1");
        return Math.ceil(Math.ceil((d-dstart)/(24*60*60*1000))/7);
    case "month":
        return d.getMonth() + 1;
    case "quarter":
        return Math.floor(d.getMonth()/3) + 1;
    case "year":
        return d.getFullYear();
    case "years":
        var years = [], cy = d.getFullYear();
        for (var i=2007; i<=cy; i++) years.push(i);
        return years;
    case "months": 
        return [1,2,3,4,5,6,7,8,9,10,11,12];
    case "quarters":
        return [1,2,3,4];
    case "weeks":
        var weeks = [];
        for (var i=1;i<55;i++) {
            weeks.push(i);
        }
        return weeks;
    case "hours":
        var hours = [];
        for (var i=0;i<24;i++) {
            hours.push(i);
        }
        return hours;
    case "minutes": case "seconds":
        var minutes = [];
        for (var i=0;i<60;i++) {minutes.push(i);}
        return minutes;
    case "yestoday":
        d.setDate(d.getDate()-1);
        return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
    case "lastweek":
        d.setDate(d.getDate()-7);
        return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
    case "lastMonthWeek": 
        d.setMonth(d.getMonth()-1);
        var dstart = new Date(d.getFullYear(), "0", "1");
        return Math.ceil(Math.ceil((d-dstart)/(24*60*60*1000))/7);
    default:
        return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
    }
};

$.setCurrentMenu = function(subId, parentId) {
    parentId = parentId ? '#'+parentId : '';
    subId = subId ? parentId+' #'+subId : subId;
    if (!subId) return;
    $('#main-nav ' + subId).addClass('current');
};

$.setDateController = function(type) {
    var timeLabels = ['Year', 'Quarter', 'Month', 'Week', 'Day', 'Hour', 'Minute'];
    if (!type) type = 'day';
    for (var i = 0; i < timeLabels.length; i++) {
        var it = timeLabels[i], lt = it.toLowerCase(), 
            time = $.getDate(lt), times = $.getDate(lt + "s");
        $('#end' + it).setOptions(times).val(time);
        if (type == 'year' || type == 'quarter' || type == 'month'){
            if (it == 'Year') time = time - 1;
        } else if (type == 'week') {
            if (it == 'Week') {
                var temp = time;
                time = $.getDate('lastMonthWeek');
                if (temp < time) {
                    $('#startYear').val($.getDate('year')-1);
                }
            }
        } else if (type == 'second') {
            if (it == 'Hour') time = time - 1;
        }
        $('#start' + it).setOptions(times).val(time);
    }
    
    var stime = $.getDate();
    $('#endDate').val(stime).datepicker({
        dateFormat: 'yy-mm-dd',
        onSelect: function(selectedDate) {
            $("#startDate").datepicker("option", "maxDate", selectedDate);
        }
    });
    
    $('#startDate').datepicker({
        dateFormat: 'yy-mm-dd',
        maxDate: stime,
        onSelect: function(selectedDate) {
            $("#endDate").datepicker("option", "minDate", selectedDate);
        }
    });
    if (type == 'day') stime = $.getDate('lastweek');
    else if (type == 'hour') stime = $.getDate('yestoday');
    $('#startDate').val(stime);
    $( "#endDate" ).datepicker( "option",  "minDate", stime );
    
};

$.fn.setLoading = function() {
    return $(this).each(function(){
        var height = $(this).css('height'),
            width = $(this).css('width');
        if (!height) {
            height = '200px';
            $(this).css({height: height});
        }
        var layer = $('<div><image style="vertical-align: middle;" src="/emip/resources/images/loading.gif"/></div>').css({
            width: height,
            height: width,
            position: 'absolute',
            top: 0,
            left: 0,
            'text-algin': 'center'
        });
        $(this).css({position: 'relative'}).append(layer);
    });
};